package org.springframework.license.validate;

import org.springframework.license.exception.LicenseException;
import org.springframework.license.vo.LicenseVerifyParam;
import org.springframework.license.vo.ServiceKeyStoreParam;
import de.schlichtherle.license.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * @Title LicenseVerify
 * @Author zhijun.Guo
 * @Email tiankong061015@163.com
 * @Time 2024/9/3 00:27
 * @Description
 */
@Slf4j
public class LicenseVerify {

    /**
     * 安装License证书
     */
    public synchronized LicenseContent install(LicenseVerifyParam param){
        LicenseContent result = null;
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //1. 安装证书
        try{
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(initLicenseParam(param));
            licenseManager.uninstall();
//            log.info("start install license,param: {}", param.toString());
            result = licenseManager.install(new File(param.getLicensePath()));
            log.info(MessageFormat.format("certificate install success，valid date between ：{0} - {1}",format.format(result.getNotBefore()),format.format(result.getNotAfter())));
        }catch (Exception e){
            log.error("certificate install failed, message = {0}",e);
            throw new LicenseException(LicenseException.Error.CERTIFICATE_INSTALL_FAILED);
        }

        return result;
    }

    /**
     * 校验License证书
     */
    public void validate(){
        LicenseManager licenseManager = LicenseManagerHolder.getInstance(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //2. 校验证书
        try {

            LicenseContent licenseContent = licenseManager.verify();

//            log.info(MessageFormat.format("certificate validate success，valid date between：{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
            // 模拟授权失败
//            throw new LicenseException(LicenseException.Error.CERTIFICATE_AUTHORIZATION_EXPIRED);
        }catch (Exception e){
//            log.error("certificate validate failed, message = {0}",e);
            throw new LicenseException(LicenseException.Error.CERTIFICATE_AUTHORIZATION_FAILED);
        }
    }

    /**
     * 初始化证书生成参数
     * @param param License校验类需要的参数
     * @return de.schlichtherle.license.LicenseParam
     */
    private LicenseParam initLicenseParam(LicenseVerifyParam param){
        Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

        CipherParam cipherParam = new DefaultCipherParam(param.getStorePass());

        KeyStoreParam publicStoreParam = new ServiceKeyStoreParam(LicenseVerify.class
                ,param.getPublicKeysStorePath()
                ,param.getPublicAlias()
                ,param.getStorePass()
                ,null);

        return new DefaultLicenseParam(param.getSubject()
                ,preferences
                ,publicStoreParam
                ,cipherParam);
    }
}
